package org.duang.handles;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpHeaders;
import org.duang.common.dto.DRLDto;
import org.duang.common.exceptios.ServiceException;
import org.duang.config.Config;
import org.duang.kit.ToolsKit;
import org.duang.proxy.DuangProxy;

/**
 * 用于初始一些请求参数到Request或Response对象
 * 
 * @author laotang
 *
 */
public class InitHandle implements IHandle {

	private static final String SERVLET_FLAG = "servlet";
	private static final String APTCHA_FLAG = "aptcha";
	

	@Override
	public void execute(String target, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 如果是访问servlet及验证码的话，就直接退出
		if (target.endsWith(SERVLET_FLAG) || target.indexOf(APTCHA_FLAG) > -1 || target.indexOf(".") > -1 || target.indexOf("#") > -1 || target.indexOf(";") > -1) {
			return;
		}
		if (!ToolsKit.isSecurityUrl(target)) { 
			if(target.indexOf(Config.getSecurityLoginUrl()) == -1) {
				throw new ServiceException().setCode(403).setMessage("[ "+ target +" ] not exist, access denied! ");
			}
		}
		//设置DRL线程ID名称
		setRequestLinkThreadId(request, response);
	}
	
	private void setRequestLinkThreadId(HttpServletRequest request, HttpServletResponse response) {
		if (Config.isEnableDRL()) {
			if(request.getRequestURI().equals("/")) return;
			String requestLinkThreadId = (String)request.getAttribute(Config.DUANG_LINK_REQUEST_THREAD_ID);
			if (ToolsKit.isEmpty(requestLinkThreadId)) {
				request.setAttribute(Config.DUANG_LINK_REQUEST_THREAD_ID, Config.getProductCode() + "_" + Thread.currentThread().getId());
				requestLinkThreadId = request.getAttribute(Config.DUANG_LINK_REQUEST_THREAD_ID).toString();
			}
			DRLDto drlDto = new DRLDto();
			drlDto.setClientIp(request.getRemoteAddr());
			drlDto.setMethod(request.getMethod());
			drlDto.setParams(ToolsKit.toJsonString(request.getParameterMap()));
			drlDto.setProtocol(request.getProtocol());
			drlDto.setRequestTime(new Date());
			drlDto.setUri(request.getRequestURI());
			drlDto.setHeader(request.getHeader(HttpHeaders.USER_AGENT));
			
			DuangProxy.drlDtoMap.put(requestLinkThreadId, drlDto);
		}
	}
}
